package com.banhujiu.spider.region.factory

import com.banhujiu.spider.region.IOQueue
import com.banhujiu.spider.region.conf.areaTableName
import com.banhujiu.spider.region.conf.sqlInsertSize
import com.banhujiu.spider.region.enties.FileEntry
import com.banhujiu.spider.region.enties.RegionEntry
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import java.io.FileWriter

/**
 * @author banhujiu
 * @date 2017/11/22 0022 16:45
 */
class IOWrite(private val ioQueue: IOQueue, private val file: FileEntry) : Runnable {
    private val logger: Logger = LogManager.getLogger(this::class.java.name)

    override fun run() {
        while (!Thread.interrupted()) {
            val take: RegionEntry = ioQueue.take()
            val writeLock = file.readWriteLock.writeLock()
            try {
                val count = file.count.incrementAndGet()
                val fw = FileWriter(file.file, true)
                var info = ""
                val toSql: String = "('" + take.code + "' , '" + take.name + "' , " + take.level + " , '" + take.pCode + "')"
                info += when {
                    count == 1 -> "\nINSERT INTO `$areaTableName` (code , name , level , p_code) VALUES $toSql"
                    count >= sqlInsertSize -> {
                        file.count.set(0)
                        ",$toSql;"
                    }
                    else -> "," + toSql
                }
                fw.write(info)
                fw.flush()
            } finally {
                file.readWriteLock.unlockWrite(writeLock)
            }
        }
    }
}
